//package org.ricks.action.rpc;
//
//import org.ricks.net.action.context.session.TcpSessionAdapter;
//import org.ricks.net.action.parser.ProtocolParserEnum;
//import org.ricks.net.action.parser.TypeReference;
//import org.ricks.net.action.rpc.RpcClientV1;
//import org.ricks.net.action.rpc.RpcMetrics;
//import org.ricks.net.transport.AioQuickClient;
//import org.ricks.net.transport.AioSession;
//
//import java.util.concurrent.*;
//import java.util.concurrent.atomic.AtomicInteger;
//
//public class RpcClientTest1 {
//    public static void main(String[] args) throws Exception {
//        // 1. 初始化客户端
//        RpcHandler rpcHandler = new RpcHandler();
//        AioQuickClient aioQuickClient = new AioQuickClient("localhost", 8888, new RpcProtocol(), rpcHandler);
//        aioQuickClient.setReadBufferSize(1024 * 1024);
//        aioQuickClient.setWriteBuffer(1024 * 1024, 1024 * 1024);
//        AioSession session = aioQuickClient.start();
//
//        RpcMetrics rpcMetrics = new RpcMetrics();
//        RpcClientV1 rpcClientV1 = new RpcClientV1(new TcpSessionAdapter(session),
//                ProtocolParserEnum.STRING.getParser(), 3000, rpcMetrics);
//        rpcHandler.addRpcClient(session, rpcClientV1);
//
//        // 2. 使用单独管理的线程池（ExecutorService不支持AutoCloseable）
//        ExecutorService virtualExecutor = Executors.newVirtualThreadPerTaskExecutor();
//        ScheduledExecutorService reporter = Executors.newSingleThreadScheduledExecutor();
//
//        try {
//            reporter.scheduleAtFixedRate(() -> {
//                System.out.println("=== Client Metrics ===");
//                rpcMetrics.printStats();
//            }, 10, 10, TimeUnit.SECONDS);
//
//            // 3. 使用CountDownLatch替代忙等待
//            final int totalRequests = 100_000;
//            CountDownLatch completionLatch = new CountDownLatch(totalRequests);
//            AtomicInteger successCount = new AtomicInteger();
//            long startTime = System.currentTimeMillis();
//
//            // 4. 优化信号量使用：避免在主线程获取
//            Semaphore semaphore = new Semaphore(1000);
//
//            for (int i = 0; i < totalRequests; i++) {
//                // 使用虚拟线程提交任务
//                virtualExecutor.submit(() -> {
//                    try {
//                        semaphore.acquire();
//                        CompletableFuture<String> future = rpcClientV1.invoke(
//                                (short) 10, "smart-rpc-ricks", new TypeReference<String>() {});
//
//                        future.whenComplete((str, ex) -> {
//                            semaphore.release();
//                            completionLatch.countDown();
//
//                            if (ex == null) {
//                                int count = successCount.incrementAndGet();
//                                if (count % 10_000 == 0) {
//                                    System.err.printf("Completed %,d requests in %d ms%n",
//                                            count, System.currentTimeMillis() - startTime);
//                                }
//                            }
//                        });
//                    } catch (Exception e) {
//                        semaphore.release();
//                        System.err.println("Request failed: " + e.getMessage());
//                        completionLatch.countDown();
//                    }
//                });
//            }
//
//            // 5. 高效等待完成
//            completionLatch.await();
//            long endTime = System.currentTimeMillis();
//
//            System.out.println("=================================");
//            System.out.printf("All %d requests completed in %d ms%n",
//                    totalRequests, endTime - startTime);
//            System.out.println("Successful requests: " + successCount.get());
//            rpcMetrics.printStats();
//        } finally {
//            // 6. 确保资源关闭
//            virtualExecutor.shutdown();
//            reporter.shutdown();
//            if (!virtualExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
//                virtualExecutor.shutdownNow();
//            }
//            if (!reporter.awaitTermination(10, TimeUnit.SECONDS)) {
//                reporter.shutdownNow();
//            }
//            aioQuickClient.shutdown();
//        }
//    }
//}